package com.xjd.edu.toolkit.helper;

import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;

/**
 * @author wangyu
 * @since 2022/3/4
 */
public final class BeanHelper {

    /**
     * 类型转换，本质上是通过 org.springframework.beans.BeanUtils#copyProperties(Object, Object) 实现
     *
     * @param source     转换源对象
     * @param targetType 目标类型参数不能为空，且必须支持 Class#newInstance()
     * @param <S>
     * @param <T>
     * @return 返回转换目标对象，源对象为空时直接返回NULL
     * @see BeanUtils#copyProperties(Object, Object)
     */
    @SneakyThrows
    public static <S, T> T convert(S source, Class<T> targetType) {
        if (source == null) {
            return null;
        }
        Assert.notNull(targetType, "转换目标类型不能为空");
        final T target = targetType.newInstance();
        BeanUtils.copyProperties(source, target);
        return target;
    }

}
